import { useContext, useEffect, useState } from "react"
import { AppContext } from "../../Context/AppContext"
import { useNavigate, useParams } from "react-router-dom"

export default function Edit(){
    const [formData, setFormData] = useState({ title: "", body: "" })
    const {token,user} = useContext(AppContext)
    const [errors, setErrors] = useState({})
    const navigate = useNavigate()
    const {id} = useParams()
      const getPost = async () => {
        const res = await fetch(`/api/posts/${id}`);
        const data = await res.json();
       
       if(res.ok){
        
        
        setFormData(data.data);
       }
    }
    useEffect(() => {
        getPost();
    }, [id]);
    const handleSubmit = async (e) => {
        e.preventDefault()
        const res = await fetch(`/api/posts/${id}`,{
            method: 'put',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(formData)
        })
        const data = await res.json()
        if(data.errors||!res.ok){
            setErrors(data.errors)
        }else{
              setFormData({ title: "", content: "" })
              navigate('/')
        }
    
    }
    return (
        <>
            <h1 className="title">编辑文章</h1>
            <form onSubmit={handleSubmit} className="w-1/2 mx-auto space-y-6">
                <div>
                    <input type="text" value={formData.title} onChange={(e) => setFormData({...formData, title: e.target.value })} placeholder="标题" />
                    {errors.title && <p className="error">{errors.title}</p>}
                </div>
                <div>
                    <textarea placeholder="内容" value={formData.body} onChange={(e) => setFormData({...formData, body: e.target.value })} rows="10" cols="50"></textarea>
                    {errors.body && <p className="error">{errors.body}</p>}
                    </div>
                <div><button className="primary-btn" type="submit">更新</button></div>
            </form>
        </>
    )
}